<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单号" prop="orderNo">
        <el-input
          v-model="queryParams.orderNo"
          placeholder="请输入订单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="物流单号" prop="logisticsNo">
        <el-input
          v-model="queryParams.logisticsNo"
          placeholder="请输入物流单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- 状态字段暂时隐藏 -->
      <!-- <el-form-item label="状态" prop="logisticsStatus">
        <el-select v-model="queryParams.logisticsStatus" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.ec_logistics_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['fun:logistics:add']"
        >新增发货</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['fun:logistics:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['fun:logistics:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['fun:logistics:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="logisticsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="物流信息ID" align="center" prop="logisticsId" />
      <el-table-column label="订单号" align="center" prop="orderNo" />
      <el-table-column label="物流公司" align="center" prop="logisticsCompanyName" />
      <el-table-column label="物流公司代码" align="center" prop="logisticsCompany" width="120" />
      <el-table-column label="物流单号" align="center" prop="logisticsNo" />

      <!-- 暂时隐藏的列 -->
      <!-- <el-table-column label="创建组织" align="center" width="120">
        <template slot-scope="scope">
          <span>{{ getDeptName(scope.row.orgId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="物流状态" align="center" prop="logisticsStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.ec_logistics_status" :value="scope.row.logisticsStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="发件人姓名" align="center" prop="senderName" />
      <el-table-column label="发件人电话" align="center" prop="senderPhone" />
      <el-table-column label="发件人地址" align="center" prop="senderAddress" />
      <el-table-column label="收件人姓名" align="center" prop="receiverName" />
      <el-table-column label="收件人电话" align="center" prop="receiverPhone" />
      <el-table-column label="收件人地址" align="center" prop="receiverAddress" /> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['fun:logistics:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['fun:logistics:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改物流信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="订单" prop="orderNo">
          <id-selector
            v-model="form.orderNo"
            placeholder="请选择订单"
            dialog-title="选择订单"
            :api-function="listOrder"
            :get-api-function="getOrder"
            id-field="orderNo"
            name-field="orderNo"
            id-label="订单ID"
            name-label="订单号"
            search-label="订单号"
            search-placeholder="请输入订单号"
            :extra-columns="[{prop: 'totalAmount', label: '订单金额'}, {prop: 'orderStatus', label: '订单状态'}]"
          />
        </el-form-item>
        <el-form-item label="物流类型" prop="logisticsType">
          <el-radio-group v-model="form.logisticsType">
            <el-radio :label="1">快递配送</el-radio>
            <el-radio :label="2">同城配送</el-radio>
            <el-radio :label="3">虚拟商品</el-radio>
            <el-radio :label="4">用户自提</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="物流单号" prop="logisticsNo" v-if="form.logisticsType === 1">
          <el-input v-model="form.logisticsNo" placeholder="请输入物流单号" />
        </el-form-item>
        <el-form-item label="物流公司" prop="logisticsCompany" v-if="form.logisticsType === 1">
          <id-selector
            v-model="form.logisticsCompany"
            placeholder="请选择物流公司"
            dialog-title="选择物流公司"
            :api-function="listLogisticsCompany"
            :get-api-function="getLogisticsCompany"
            id-field="id"
            name-field="expName"
            id-label="物流公司ID"
            name-label="物流公司名称"
            search-label="物流公司名称"
            search-placeholder="请输入物流公司名称"
            :extra-columns="[{prop: 'com', label: '物流公司代码'}, {prop: 'phone', label: '联系电话'}, {prop: 'url', label: '官网地址'}]"
            @change="handleLogisticsCompanyChange"
          />
        </el-form-item>
        <!-- 物流状态设置默认值，暂时隐藏 -->
        <!-- <el-form-item label="物流状态" prop="logisticsStatus">
          <el-select v-model="form.logisticsStatus" placeholder="请选择物流状态">
            <el-option
              v-for="dict in dict.type.ec_logistics_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item> -->

        <!-- 暂时隐藏的字段 -->
        <!-- <el-form-item label="发货时间" prop="shipTime">
          <el-date-picker clearable
            v-model="form.shipTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择发货时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="预计到达时间" prop="estimatedArrivalTime">
          <el-date-picker clearable
            v-model="form.estimatedArrivalTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择预计到达时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="实际到达时间" prop="actualArrivalTime">
          <el-date-picker clearable
            v-model="form.actualArrivalTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择实际到达时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listLogistics, getLogistics, delLogistics, addLogistics, updateLogistics, wechatShipping } from "@/api/fun/logistics"
import { getDept } from "@/api/system/dept"
import { listOrder, getOrder } from "@/api/fun/order"
import { listLogisticsCompany, getLogisticsCompany } from "@/api/fun/logisticsCompany"
import IdSelector from "@/components/IdSelector"

export default {
  components: {
    IdSelector
  },
  name: "Logistics",
  dicts: ['ec_logistics_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 物流信息表格数据
      logisticsList: [],
      // 部门名称缓存
      deptNameCache: {},
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        logisticsType: [
          { required: true, message: "请选择物流类型", trigger: "change" }
        ],
        // 物流单号：快递配送时必填
        logisticsNo: [
          {
            validator: (rule, value, callback) => {
              if (this.form.logisticsType === 1) {
                // 快递配送时必填
                if (!value) {
                  callback(new Error('快递配送时，物流单号不能为空'));
                } else {
                  callback();
                }
              } else {
                // 其他类型时不验证
                callback();
              }
            },
            trigger: ['blur', 'change']
          }
        ],
        // 物流公司：快递配送时必填
        logisticsCompany: [
          {
            validator: (rule, value, callback) => {
              if (this.form.logisticsType === 1) {
                // 快递配送时必填
                if (!value) {
                  callback(new Error('快递配送时，物流公司不能为空'));
                } else {
                  callback();
                }
              } else {
                // 其他类型时不验证
                callback();
              }
            },
            trigger: ['blur', 'change']
          }
        ]
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderNo: null,
        logisticsCompany: null,
        logisticsNo: null,
        logisticsStatus: null,
        senderName: null,
        senderPhone: null,
        senderAddress: null,
        receiverName: null,
        receiverPhone: null,
        receiverAddress: null,
      }
    }
  },
  created() {
    this.getList()
  },
  mounted() {
    // 监听表单提交事件
    this.$eventBus.$on('refreshLogisticsList', () => {
      this.getList()
    })
  },
  beforeDestroy() {
    // 移除事件监听器
    this.$eventBus.$off('refreshLogisticsList')
  },
  methods: {    /** 根据部门ID获取部门名称 */
    getDeptName(deptId) {
      if (!deptId) return '-'
      if (this.deptNameCache[deptId]) {
        return this.deptNameCache[deptId]
      }
      // 异步获取部门名称
      getDept(deptId).then(response => {
        this.$set(this.deptNameCache, deptId, response.data.deptName)
        // 强制更新视图
        this.$forceUpdate()
      }).catch(() => {
        this.$set(this.deptNameCache, deptId, '未知组织')
        this.$forceUpdate()
      })
      return deptId // 先显示ID，异步加载完成后显示名称
    },
    /** 查询物流信息列表 */
    getList() {
      this.loading = true
      listLogistics(this.queryParams).then(response => {
        this.logisticsList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.logisticsId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        logisticsId: null,
        orderNo: null,
        logisticsType: 1, // 默认选择快递配送
        logisticsCompany: null,
        logisticsCompanyName: null,
        logisticsNo: null,
        logisticsStatus: '0', // 设置默认状态为待发货
        shipTime: null,
        estimatedArrivalTime: null,
        actualArrivalTime: null,
        senderName: null,
        senderPhone: null,
        senderAddress: null,
        receiverName: null,
        receiverPhone: null,
        receiverAddress: null,
        remark: null
      }
      this.resetForm("form")
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加物流信息"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const logisticsId = row.logisticsId || this.ids[0]
      const obj = { path: "/fun/logistics-form", query: { logisticsId: logisticsId } }
      this.$tab.openPage(obj)
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.logisticsId != null) {
            updateLogistics(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            // 先添加物流信息
            addLogistics(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")

              // 如果有订单号，调用微信发货接口
              if (this.form.orderNo) {
                // 查询订单详情获取收货地址手机号
                getOrder(this.form.orderNo).then(orderResponse => {
                  const order = orderResponse.data

                  // 构建微信发货数据
                  const wechatData = {
                    orderId: order.orderId,
                    logistics_type: this.form.logisticsType
                  }

                  // 快递配送时添加物流信息
                  if (this.form.logisticsType === 1) {
                    wechatData.shipping_list = [{
                      tracking_no: this.form.logisticsNo,
                      express_company: this.form.logisticsCompany
                    }]

                    // 添加收货联系方式
                    if (order.receiverPhone) {
                      wechatData.contact = {
                        receiver_contact: order.receiverPhone
                      }
                    }
                  }

                  // 调用微信发货接口
                  wechatShipping(wechatData).then(wechatResponse => {
                    this.$modal.msgSuccess("微信发货通知发送成功")
                  }).catch(error => {
                    console.error('微信发货失败:', error)
                    this.$modal.msgError("微信发货通知发送失败: " + (error.msg || error.message || '未知错误'))
                  })
                }).catch(error => {
                  console.error('查询订单详情失败:', error)
                  this.$modal.msgError("查询订单详情失败")
                })
              }

              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const logisticsIds = row.logisticsId || this.ids
      this.$modal.confirm('是否确认删除物流信息编号为"' + logisticsIds + '"的数据项？').then(function() {
        return delLogistics(logisticsIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('fun/logistics/export', {
        ...this.queryParams
      }, `logistics_${new Date().getTime()}.xlsx`)
    },
    /** 物流公司选择变化处理 */
    handleLogisticsCompanyChange(id, selectedItem) {
      if (selectedItem) {
        this.form.logisticsCompany = selectedItem.id
        this.form.logisticsCompanyName = selectedItem.expName
      } else {
        this.form.logisticsCompany = null
        this.form.logisticsCompanyName = null
      }
    },
    // API方法
    listOrder,
    getOrder,
    listLogisticsCompany,
    getLogisticsCompany
  }
}
</script>
